//
//  MNDBBSViewController.m
//  minidai
//
//  Created by Steven.Yung on 2017/6/3.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDBBSViewController.h"
#import "MNDLoginUserModel.h"
#import "RSAUtil.h"
#import "MNDLoginNaviViewController.h"
#import "SYWebLoadingProgress.h"
/*! 网页版登录 */
#define kWebPageLogin             @"miniwangdai.com/login"
/*! 网页版迷你金服首页 */
#define kPCHomePage               @"https://www.miniwangdai.com/"
/*! 论坛退出账户 */
#define kBBSLogout                @"miniwangdai.com/logout"

@interface MNDBBSViewController () <UIWebViewDelegate>

@property (strong, nonatomic) UIWebView *webView;

@property (copy, nonatomic) NSString *absoluteUrl;

@property (strong, nonatomic) UIButton *closeButton;

@property (nonatomic) BOOL shouldReload;

@property (strong, nonatomic) SYWebLoadingProgress *webLoadingProgress;

@end

@implementation MNDBBSViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (@available(iOS 11.0, *)) {
        self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    [self initialWebView];
    [self initialBackButton];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController setNavigationBarHidden:self.shouldHideNaviBarWhenDismiss animated:NO];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initialWebView {
    self.webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    self.webView.backgroundColor = kColorBackground;
    self.webView.scrollView.bounces = NO;
    self.webView.scalesPageToFit = YES;
    
    self.webView.delegate = self;
    NSString *urlStr = [NSString stringWithFormat:@"%@%@", BroswerHeadURL, [NSString urlEncodeStr:self.url]];
    self.title = @"蜜柚社区";
    if (self.isCustomService) {
        self.title = @"在线客服";
    }
    NSURL *url = [NSURL URLWithString: urlStr];
    
    if ([MNDLoginUserModel isUserLogin]) {

        NSURLRequest *request = [self configRequestHeaderFileds:url];

        [self.webView loadRequest:request];
    } else {
        NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:60.0];
        [self.webView loadRequest:request];
    }
    
    [self.view addSubview:self.webView];
    
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
//    [self setCookies];
    
    [self.view beginLoading];
}

- (NSMutableURLRequest *)configRequestHeaderFileds: (NSURL *)url {
    // 添加请求头信息
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:60.0];
    
    MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
    NSString *userCode = [self rsaEncode:user.user_code];
    
    [request setValue:userCode forHTTPHeaderField:@"USERCODE"];
    
    return request;
}

- (NSString *)rsaEncode:(NSString *)rsaStr {
    NSString *encryText = [RSAUtil encryptString:[NSString stringWithFormat:@"%@", rsaStr] publicKey:RSA_PUBLIC_KEY];
    NSString *unreserved = @"";
    NSMutableCharacterSet *allowed = [NSMutableCharacterSet alphanumericCharacterSet];
    [allowed addCharactersInString:unreserved];
    
    NSString *encodeEncryText = [encryText stringByAddingPercentEncodingWithAllowedCharacters:allowed];
    
    return encodeEncryText;
}

- (void)initialBackButton {
    UIImage *backImage = [UIImage imageNamed:@"navi_back_btn_black"];
    
    //创建返回按钮
    UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backImage
                                                                          style:UIBarButtonItemStylePlain
                                                                         target:self
                                                                         action:@selector(backAction:)];
    //设置返回按钮的颜色
    [backBarButtonItem setTintColor:kColorBackButtonColor];
    
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    
    self.closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.closeButton setTitle:@"关闭" forState:UIControlStateNormal];
    self.closeButton.titleLabel.font = [UIFont systemFontOfSize:14.0];
    [self.closeButton setTitleColor:[UIColor colorWithRed:57/255.0 green:66/255.0 blue:64/255.0 alpha:1.0] forState:UIControlStateNormal];
    [self.closeButton addTarget:self action:@selector(closeAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.closeButton setFrame:CGRectMake(0, 0, 40, 30)];
    [self.closeButton setHidden:YES];
    
    UIBarButtonItem *closeItem = [[UIBarButtonItem alloc] initWithCustomView:self.closeButton];
    //    [closeItem setTintColor: [UIColor colorWithRed:57/255.0 green:66/255.0 blue:64/255.0 alpha:1.0]];
    
    //将两个BarButtonItem都返回给NavigationItem
    if (@available(iOS 11.0, *)) {
        self.navigationItem.leftBarButtonItems = @[backBarButtonItem, closeItem];
    } else {
        self.navigationItem.leftBarButtonItems = @[spaceItem, backBarButtonItem, closeItem];
    }
}

- (void)closeAction:(id)sender {
    [self goBackAction];
}

- (void)backAction:(id)sender {
    if (self.webView.canGoBack) {
        [self.webView goBack];
        [self.closeButton setHidden:NO];
        
        return;
    }
    
    [self goBackAction];
}

- (void)goBackAction {
    
    if (self.presentingViewController) {
        //present方式
        [self.navigationController dismissViewControllerAnimated:YES completion:^{
            
        }];
    } else{
        //push方式
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)goLoginVC {
    
    WeakSelf(self);
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
    MNDLoginNaviViewController *naviVC = [storyboard instantiateInitialViewController];
    naviVC.loginCompletedBlock = ^(BOOL loginSuccess) {
        
        if (loginSuccess) {
//            NSURL *url = [NSURL URLWithString:weakself.absoluteUrl];
//            NSURLRequest *request = [weakself configRequestHeaderFileds:url];
//            [weakself.webView loadRequest:request];
//            [weakself.view beginLoading];
            [weakself.webView reload];
        }
    };
    
    [self presentViewController:naviVC animated:YES completion:^{
        
    }];
}

- (NSMutableURLRequest *)addHTTPHeaderFieldWithRequest:(NSURLRequest *)request {
    NSMutableURLRequest *mutableRequest = [request mutableCopy];
    //来源加入header
    if (kDevice_iPad) {
        [mutableRequest addValue:@"iPad" forHTTPHeaderField:@"WERTYUIOP"];
    } else {
        [mutableRequest addValue:@"iPhone" forHTTPHeaderField:@"WERTYUIOP"];
    }
    
    return mutableRequest;
}

#pragma mark - UIWebView Delegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    NSMutableURLRequest *mutableRequest = [self addHTTPHeaderFieldWithRequest:request];
    request = [mutableRequest copy];
    
    NSString *absoluteStr = request.URL.absoluteString;
    NSLog(@"web url: %@" , absoluteStr);
    
    if ([absoluteStr  isEqualToString:kPCHomePage]) {
        return NO;
    }
    
    if ([absoluteStr isEqualToString:kBBSLogout]) {
        return NO;
    }
    
    if (![absoluteStr containsString:kWebPageLogin]) {
        self.absoluteUrl = absoluteStr;
        
    }
    if ([absoluteStr containsString:kWebPageLogin]) {
        dispatch_async(dispatch_get_main_queue(), ^{
           [self goLoginVC];
//            self.shouldReload = YES;
        });
        
        return NO;
    }
    
    return YES;
}
- (SYWebLoadingProgress *)webLoadingProgress {
    if (!_webLoadingProgress) {
        _webLoadingProgress = [[SYWebLoadingProgress alloc] init];
        _webLoadingProgress.progressColor = kColorBlue;
        _webLoadingProgress.progressStyle = LoadingPregressType_Noraml;
    }
    
    if ([self.navigationController.navigationBar isHidden]) {
        _webLoadingProgress.frame = CGRectMake(0, 20, kScreenWidth, 2);
        
    } else {
        CGFloat yPosition = 64.0;
        if (kScreenHeight >= 812) {
            yPosition = 88;
        }
        _webLoadingProgress.frame = CGRectMake(0, yPosition, kScreenWidth, 2);
//        [self.view.layer insertSublayer:_webLoadingProgress atIndex:0];
    }
    [self.webView.layer addSublayer:_webLoadingProgress];
    
    return _webLoadingProgress;
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
    
    [self.webLoadingProgress startProgressAnimation];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    
    //    取消长按webView上的链接弹出actionSheet的问题
    [webView stringByEvaluatingJavaScriptFromString: @"document.documentElement.style.webkitUserSelect='none';"];
    if ([webView.request.URL.absoluteString containsString:kCustomerServiceURLStr]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.navigationController setNavigationBarHidden:NO animated:NO];
            [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByClassName('chat-view-window-header-back')[0].style.display='none';"];
            self.title = @"在线客服";
        });
    }
    [self.webLoadingProgress completedProgressAnimation];
    [self.view endLoading];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    [self.webLoadingProgress completedProgressAnimation];
    if (error.code == -999) {
        return;
    }
    
    if (error.code == 102 || error.code == -102) {
        return;
    }
    
    [NetworkProgressHUD showHudNetworkError:error];
    WeakSelf(self);
    SYBlankPageType blankType = [weakself.view blankPageTypeWithError:error];
    [self.view configBlankPage:blankType hasData:NO reloadButtonBlock:^(id sender) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakself.webView reload];
            //            [weakself.view beginLoading];
        });
        
    }];
}

- (void)setCookies {
    if ([MNDLoginUserModel isUserLogin]) {
        //        [self clearWebViewCookies];
        
        MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
        
        NSDictionary *dictCookieUId;
        
        dictCookieUId = @{
                          NSHTTPCookieName: @"user_code",
                          NSHTTPCookieValue: user.user_code,
                          NSHTTPCookiePath: @"/",
                          NSHTTPCookieVersion: @"0",
                          NSHTTPCookieDomain: @".miniwangdai.com"
                          };
        NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:dictCookieUId];
        
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
